#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("Serial");

    mSerial = new QSerialPort(this);
    updateSerialPorts();

    mSerialScanTimer = new QTimer(this);
    mSerialScanTimer->setInterval(5000);
    mSerialScanTimer->start();

    connect(mSerialScanTimer, &QTimer::timeout,
            this, &MainWindow::updateSerialPorts);

    connect(ui->lineEdit, &QLineEdit::returnPressed,
            this, &MainWindow::on_send_Button_clicked);

    connect(mSerial, &QSerialPort::readyRead,
            this, &MainWindow::serialReadyRead);
    //绘图部分

    mData = QSharedPointer<QCPGraphDataContainer>(new QCPGraphDataContainer);

    /* 绘图初始化 */
    ui->plot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);
    ui->plot->legend->setVisible(true);
    QFont legendFont = font();
    legendFont.setPointSize(10);
    ui->plot->legend->setFont(legendFont);
    ui->plot->legend->setSelectedFont(legendFont);
    ui->plot->legend->setSelectableParts(QCPLegend::spItems);
    ui->plot->yAxis->setLabel("Magnitude");
    ui->plot->xAxis->setLabel("Sample");
    ui->plot->clearGraphs();
    ui->plot->addGraph();

    ui->plot->graph()->setPen(QPen(Qt::black));
    ui->plot->graph()->setData(mData);
    ui->plot->graph()->setName("STM32 ADC2025.11.23");
}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::updateSerialPorts()
{
    mSerialPorts = QSerialPortInfo::availablePorts();

    ui->serialComboBox->clear();
    for (QSerialPortInfo port : mSerialPorts) {
        ui->serialComboBox->addItem(port.portName(), port.systemLocation());
    }
}


void MainWindow::on_connect_pushButton_clicked()
{

    ui->connect_pushButton->setEnabled(false);
    QString serialLoc = ui->serialComboBox->currentData().toString();
      if (mSerial->isOpen()) {
        qDebug("Serial already connected, disconnecting!");// << "Serial already connected, disconnecting!";
        mSerial->close();
    }

    mSerial->setPortName(serialLoc);
    mSerial->setBaudRate(QSerialPort::Baud9600);
    mSerial->setDataBits(QSerialPort::Data8);
    mSerial->setParity(QSerialPort::NoParity);
    mSerial->setStopBits(QSerialPort::OneStop);
    mSerial->setFlowControl(QSerialPort::NoFlowControl);

    if(mSerial->open(QIODevice::ReadWrite)) {
        qDebug("SERIAL: OK!") ;
    } else {
        qDebug("SERIAL: ERROR!") ;
    }
    ui->connect_pushButton->setEnabled(true);
}
void MainWindow::on_send_Button_clicked()
{
    if (mSerial->isOpen()) {

        QString str= ui->lineEdit->text();
        ui->lineEdit->clear();
        str.append("\r\n");
        mSerial->write(str.toLocal8Bit());
    } else {
        qDebug( "Serial port not connected!");
    }

}
void MainWindow::serialReadyRead()
{
    // 1. 先把所有收到的数据追加到缓存
    mRecvBuffer.append(mSerial->readAll());

    // 2. 按照 "\r\n" 切分消息（ESP32 默认以 \r\n 结尾）
    int index;
    while ((index = mRecvBuffer.indexOf("\r\n")) != -1)
    {
        // 取出一条完整消息
        QByteArray line = mRecvBuffer.left(index);
        mRecvBuffer.remove(0, index + 2); // 删除包括 \r\n

        // 转 QString
        QString str = QString::fromUtf8(line);

        // 显示到文本框
        ui->outputTextBrowser->insertPlainText(str + "\n");
        QScrollBar *sb = ui->outputTextBrowser->verticalScrollBar();
        sb->setValue(sb->maximum());

        // 解析 sample: x y 结构
        if (str.startsWith("sample:", Qt::CaseInsensitive))
        {
            QStringList parts = str.split(" ");
            if (parts.size() == 3)
            {
                double num = parts.at(1).toDouble();
                double mag = parts.at(2).toDouble();

                qDebug() << "Got sample" << num << mag;

                // 加入绘图
                mData->add(QCPGraphData(num, mag));
                ui->plot->rescaleAxes();
                ui->plot->replot();
            }
        }
    }
}


void MainWindow::on_saveGraphButton_clicked()
{
    //step1：生成txt文件
   /* QString filename = QFileDialog::getSaveFileName(this,
                                                    tr("Save pdf"), "",
                                                    tr("Pdf files (*.txt)"));

    if (!filename.isEmpty()) {
        //ui->plot->savePdf(filename);

        QFile file(filename);//文件命名
        if (!file.open(QFile::WriteOnly | QFile::Text))     //检测文件是否打开
        {
            QMessageBox::information(this, "Error Message", "Please Select a Text File!");
            return;
        }
        QTextStream out(&file);                 //分行写入文件
        out << ui->outputTextBrowser->toPlainText();
    }*/

    //step2：将描述和文件名存入数据库
    QSqlDatabase ldb = QSqlDatabase::addDatabase("QODBC");
    ldb.setDatabaseName("DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};FIL={MS Access};DBQ=E:/serialPortTest/my.accdb");

    QSqlQuery mquery;
    bool ok = ldb.open();
    qDebug( "!");
    if(ok)
    {
        qDebug( "DB connected!");
        //存数据到数据库
        mquery.next();
        bool isok=mquery.exec("Insert INTO [test] ([content], [filename]) VALUES ('tomato', '202103241043.txt')");

        //检测存入正确
        isok=mquery.exec("select * from test;");
        if (!isok)
        {
            qDebug( "DB not connected!");
            ldb.close();
        }
        mquery.next();
        mquery.seek(1);
        QString sHostName=mquery.value(1).toString();
        mquery.clear();
        ldb.close();
        qDebug()<<sHostName;
     }
    else{
         // 打开本地数据库失败，
        qDebug()<<ldb.lastError();
     }
 }

void MainWindow::on_clear_Button_clicked()
{

    mData->clear();
    ui->plot->rescaleAxes();
    ui->plot->replot();

}
